const { ccclass, property, menu } = cc._decorator


export enum Direction {
    HORIZONTAL,
    VERTICAL,
}

export enum TextProgress {
    TYPE1, //显示 加载中... xx%
    TYPE2, //显示 xx%
}


/**
 * @description 遮罩实现的进度条
 * @author mirahs
 * @email 2892727493@qq.com
 */
@ccclass
@menu("UI/MaskProgressComp")
export default class MaskProgressComp extends cc.Component {
    @property({ type: cc.Enum(Direction) })
    private direction = Direction.HORIZONTAL
    @property(cc.Node)
    private mask: cc.Node = null

    @property(cc.Label)
    private lblProgress: cc.Label = null
    @property({ type: cc.Enum(TextProgress) })
    private textProgress = TextProgress.TYPE1

    @property(cc.Node)
    private iconFolowed: cc.Node = null

    private _progressTween: cc.Tween


    private _progress: number = 0
    public get progress() {
        return this._progress
    }
    private set progress(value: number) {
        this._progress = value

        if (this.direction == Direction.VERTICAL) {
            this.mask.height = Math.floor(value * this.mask.children[0].height)
            if (this.iconFolowed) {
                this.iconFolowed.y = this.mask.y + this.mask.height
            }
        } else {
            this.mask.width = Math.floor(value * this.mask.children[0].width)
            if (this.iconFolowed) {
                this.iconFolowed.x = this.mask.x + this.mask.width
            }
        }

        if (this.lblProgress) {
            if (this.textProgress == TextProgress.TYPE1) {
                this.lblProgress.string = `加载中... ${Math.round(value * 100)}%`
            } else {
                this.lblProgress.string = `${Math.round(value * 100)}%`
            }
        }
    }


    public setProgress(value: number) {
        if (this._progressTween) {
            this._progressTween.stop()
            this._progress = null
        }

        this.progress = this.checkProgress(value)
    }

    public updateProgress(value: number) {
        if (this._progressTween) {
            this._progressTween.stop()
        }

        this._progressTween = cc.tween(this as MaskProgressComp).to(1, { progress: this.checkProgress(value) }).start()
    }


    private checkProgress(value: number): number {
        value = Math.max(value, 0)
        value = Math.min(value, 1)

        return value
    }
}
